package com.ruoyi.web.controller.iot;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.iot.domain.gb28181.SystemConfigInfo;
import com.ruoyi.iot.domain.gb28181.config.GBApiConfig;
import com.ruoyi.iot.domain.gb28181.constants.GBApiConstants;
import com.ruoyi.iot.domain.mqtt.constants.MqttApiConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 国标服务器控制器
 *
 * @Author: 陈江灿
 * @CreateTime: 2025-02-10
 */
@RestController
@RequestMapping("/iot/gb")
@Slf4j
public class IotGBController {

    @Autowired
    private GBApiConfig gbApiConfig;

    /**
     * 获取国标服务器配置信息
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:configInfo')")
    @GetMapping("/configInfo")
    public AjaxResult getConfigInfo() {
        String url = String.format(GBApiConstants.GET_CONFIGINFO_URL, gbApiConfig.getHost());
        String response = HttpRequest.get(url).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(response);
        JSONObject dataJson = jsonObject.getJSONObject("data");
        SystemConfigInfo configInfo = JSONUtil.parseObj(dataJson).toBean(SystemConfigInfo.class);
        return success(configInfo);
    }

    /**
     * 获取国标服务器资源信息
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:resourceInfo')")
    @GetMapping("/resourceInfo")
    public AjaxResult getResourceInfo() {
        String url = String.format(GBApiConstants.GET_RESOURCE_INFO_URL, gbApiConfig.getHost());
        String response = HttpRequest.get(url).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(response);
        JSONObject dataJson = jsonObject.getJSONObject("data");
        return success(dataJson);
    }

    /**
     * 分页查询国标设备
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:devices')")
    @GetMapping("/query/devices/page")
    public AjaxResult getDeviceList(@RequestParam int page, @RequestParam int count) {
        String url = String.format(GBApiConstants.GET_DEVICES_PAGE_URL, gbApiConfig.getHost()) +
                "?page=" + page + "&count=" + count;
        String response = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 推流列表查询
     *
     * @param page
     * @param count
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:pushList')")
    @GetMapping("/query/pushList")
    public AjaxResult pushList(@RequestParam int page, @RequestParam int count) {
        String url = String.format(GBApiConstants.GET_PUSH_LIST_URL, gbApiConfig.getHost()) +
                "?page=" + page + "&count=" + count;
        String response = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页查询流代理
     *
     * @param page
     * @param count
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:proxyList')")
    @GetMapping("/query/proxyList")
    public AjaxResult proxyList(@RequestParam int page, @RequestParam int count) {
        String url = String.format(GBApiConstants.GET_PROXY_LIST_URL, gbApiConfig.getHost()) +
                "?page=" + page + "&count=" + count;
        String response = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页查询云端录像
     *
     * @param page
     * @param count
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:cloudRecord')")
    @GetMapping("/cloudRecord")
    public AjaxResult cloudRecord(@RequestParam int page, @RequestParam int count) {
        String url = String.format(GBApiConstants.GET_CLOUD_RECORD_LIST_URL, gbApiConfig.getHost()) +
                "?page=" + page + "&count=" + count;
        String response = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取播放地址
     *
     * @param recordId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getPlayUrlPath')")
    @GetMapping("/getPlayUrlPath")
    public AjaxResult getPlayUrlPath(@RequestParam Integer recordId) {
        String url = String.format(GBApiConstants.GET_CLOUD_RECORD_PLAY_PATH_URL, gbApiConfig.getHost()) +
                "?recordId=" + recordId;
        String response = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改数据流传输模式
     *
     * @param deviceId
     * @param streamMode
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getTransport')")
    @GetMapping("/getTransport/{deviceId}/{streamMode}")
    public AjaxResult getTransport(@PathVariable String deviceId, @PathVariable String streamMode) {
        String url = String.format(GBApiConstants.GET_TRANSPORT_URL, gbApiConfig.getHost(), deviceId, streamMode);
        HttpResponse response = HttpRequest.post(url).execute();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response.body());
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页查询通道
     *
     * @param deviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getChannels')")
    @GetMapping("/getChannels/{deviceId}")
    public AjaxResult getChannels(@PathVariable String deviceId, @RequestParam int page, @RequestParam int count) {
        String url = String.format(GBApiConstants.GET_DEVICES_CHANNELS_URL, gbApiConfig.getHost(), deviceId);
        HttpResponse response = HttpRequest.get(url)
                .form("page", page)
                .form("count", count)
                .execute();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(response.body());
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用ID查询国标设备
     *
     * @param deviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getDeviceById')")
    @GetMapping("/getDeviceById/{deviceId}")
    public AjaxResult getDeviceById(@PathVariable String deviceId) {
        String url = String.format(GBApiConstants.GET_DEVICES_BY_ID_URL, gbApiConfig.getHost(), deviceId);
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 开启/关闭通道的音频
     * @param channelId
     * @param audio
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getChangeAudio')")
    @GetMapping("/getChangeAudio")
    public AjaxResult getChangeAudio(@RequestParam Integer channelId, @RequestParam Boolean audio) {
        String url = String.format(GBApiConstants.GET_CHANGE_AUDIO_URL, gbApiConfig.getHost());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId", channelId);
        paramMap.put("audio", audio);
        String body = HttpUtil.post(url, paramMap);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改通道的码流类型
     * @param deviceDbId
     * @param id
     * @param streamIdentification
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:updateChannelID')")
    @GetMapping("/updateChannelID")
    public AjaxResult updateChannelID(@RequestParam Integer deviceDbId, @RequestParam int id, @RequestParam String streamIdentification) {
        String url = String.format(GBApiConstants.GET_UPDATE_CHANNEL_ID_URL, gbApiConfig.getHost());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("deviceDbId", deviceDbId);
        paramMap.put("id", id);
        paramMap.put("streamIdentification", streamIdentification);
        String body = HttpUtil.post(url, paramMap);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 开始点播
     * @param deviceId
     * @param channelId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:start')")
    @GetMapping("/start")
    public AjaxResult start(@RequestParam String deviceId, @RequestParam String channelId) {
        String url = String.format(GBApiConstants.GET_START_URL, gbApiConfig.getHost(), deviceId, channelId);
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 停止点播
     * @param deviceId
     * @param channelId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:stop')")
    @GetMapping("/stop")
    public AjaxResult stop(@RequestParam String deviceId, @RequestParam String channelId) {
        String url = String.format(GBApiConstants.GET_STOP_URL, gbApiConfig.getHost(), deviceId, channelId);
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取通道同步进度
     * @param deviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:getSyncStatus')")
    @GetMapping("/getSyncStatus/{deviceId}")
    public AjaxResult getSyncStatus(@PathVariable String deviceId) {
        String url = String.format(GBApiConstants.GET_SYNC_STATUS_URL, gbApiConfig.getHost(), deviceId);
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 同步设备通道
     * @param deviceId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:devicesSync')")
    @GetMapping("/devicesSync/{deviceId}")
    public AjaxResult devicesSync(@PathVariable String deviceId) {
        String url = String.format(GBApiConstants.GET_DEVICES_SYNC_URL, gbApiConfig.getHost(), deviceId);
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询日志文件
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:logList')")
    @GetMapping("/logList")
    public AjaxResult logList() {
        String url = String.format(GBApiConstants.GET_LOG_LIST_URL, gbApiConfig.getHost());
        String body = HttpRequest.get(url).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 解析整个 JSON 对象
            JsonNode rootNode = objectMapper.readTree(body);
            // 提取 "data" 部分
            JsonNode dataNode = rootNode.path("data");
            return success(dataNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载指定日志文件
     * @param fileName
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:gb:logFile')")
    @GetMapping("/logFile/{fileName}")
    public AjaxResult logFile(@PathVariable  String fileName) {
        String url = String.format(GBApiConstants.GET_LOG_FILE_URL, gbApiConfig.getHost(), fileName);
        String body = HttpRequest.get(url).execute().body();
        HashMap<String, Object> map = new HashMap<>();
        map.put("log", body);
        return success(map);
    }


}
